/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

/*
* 生成apk包
* $ cd android
* $ ./gradlew assembleRelease
* https://facebook.github.io/react-native/docs/signed-apk-android
* */
import React, {Component} from 'react';
import {Keyboard, BackHandler, Alert, StatusBar, View, StyleSheet} from 'react-native';
import {WebView} from 'react-native-webview'
import SplashScreen from 'react-native-splash-screen'

type Props = {};
export default class App extends Component<Props> {

  // 当前应用路由状态，0 为首页，1为二级页
  navigation = 0
  // 播放器是否全屏
  fullScreen = false
  // 键盘是否被拉起
  keyboardShow = false

  componentDidMount() {
    Keyboard.addListener('keyboardDidShow', () => {
      this.keyboardShow = true
    })
    Keyboard.addListener('keyboardDidHide', () => {
      this.keyboardShow = false
    })
    BackHandler.addEventListener('hardwareBackPress', this.backHandler)
    setTimeout(() => {
      SplashScreen.hide()
    }, 3000)
  }

  onMessage = e => {
    const event = JSON.parse(e.nativeEvent.data)
    switch (event.name) {
      case 'navigation':
        this.navigation = ['/', '/singer', '/search'].some(i => i === event.data) ? 0 : 1
        break
      case 'fullScreen':
        this.fullScreen = event.data
        break
      default:
    }
  }

  confirmExit = () => {
    Alert.alert(
      'By: ChenJiYuan',
      '确定退出应用?',
      [
        {text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: '确定', onPress: () => BackHandler.exitApp()}
      ],
      { cancelable: false }
    )
  }

  backHandler = () => {
    if (this.keyboardShow) return true
    if (this.fullScreen) {
      this.refs.webview.injectJavaScript(
        'window.musicPlayer.toggleFullScreen()'
      )
      return true
    }
    if (this.navigation === 1) {
      this.refs.webview.goBack()
    } else {
      this.confirmExit()
    }
    return true
  }

  onLoadSuccess = (e) => {
    SplashScreen.hide()
  }
  onLoadError = () => {
    this.loadErrorHandler()
  }
  loadErrorHandler = () => {
    Alert.alert(
      'By: ChenJiYuan',
      '加载失败，是否重新加载?',
      [
        {text: '退出', onPress: () => BackHandler.exitApp(), style: 'cancel'},
        {text: '确定', onPress: () => this.refs.webview.reload()}
      ],
      { cancelable: false }
    )
  }

  render() {
    return (
      <View
        style={style.container}
      >
        <StatusBar
          hidden={true}
        />
        <WebView
          source={{ uri: 'http://106.12.202.4:81/' }}
          mediaPlaybackRequiresUserAction={false}
          onMessage={this.onMessage}
          ref={'webview'}
          onLoad={this.onLoadSuccess}
          onError={this.onLoadError}
        />
      </View>
    )
  }
}

const style = StyleSheet.create({
  container: {
    height: '100%'
  }
})
